#include <jni.h>
#include "jniGlue_Windowsclass.h"
#include <math.h>
#include <string.h>
#include <windows.h>
#include <stdio.h>
extern "C" {
    #include "usbdmx.h"
}
 
TSERIALLIST InterfaceList;
TDMXArray DMX_Out, DMX_In;

typedef unsigned char TDMXArray[512];
typedef char TSERIAL[16];
typedef TSERIAL TSERIALLIST[32];
typedef void (__stdcall *TGetAllConnectedInterfaces) (TSERIALLIST* SerialList);
typedef DWORD (__stdcall *TOpenLink) (TSERIAL Serial, TDMXArray *DMXOutArray, TDMXArray *DMXInArray);
typedef DWORD (__stdcall *TSetInterfaceMode) (TSERIAL Serial, unsigned char Mode);
typedef DWORD (__stdcall *TGetDeviceVersion) (TSERIAL Serial);
typedef DWORD (__stdcall *TCloseLink) (TSERIAL Serial);

JNIEXPORT void JNICALL Java_jniGlue_Windowsclass_startdmx(JNIEnv *env,jobject obj, jstring path)
{
	const char *nativeString = env->GetStringUTFChars(path, 0);
	HINSTANCE USBDMXDLL = LoadLibrary (nativeString) ;
	int i;   
	int res;
    char str[17];
    unsigned char tmp;
	TGetAllConnectedInterfaces GetAllConnectedInterfaces;
	TOpenLink OpenLink;
	TSetInterfaceMode SetInterfaceMode;
	TGetDeviceVersion GetDeviceVersion;
	
	GetAllConnectedInterfaces = (TGetAllConnectedInterfaces)GetProcAddress(USBDMXDLL, "GetAllConnectedInterfaces");
	OpenLink = (TOpenLink)GetProcAddress(USBDMXDLL, "OpenLink");
	SetInterfaceMode = (TSetInterfaceMode)GetProcAddress(USBDMXDLL, "SetInterfaceMode");
	GetDeviceVersion = (TGetDeviceVersion)GetProcAddress(USBDMXDLL, "GetDeviceVersion");

	GetAllConnectedInterfaces(&InterfaceList);
    str[16] = 0;
    memcpy(str, InterfaceList[0], 16); //befuellt den string
    
    printf("SERIAL: %s\n", str);
    printf("VERSION: %d\n", GetDeviceVersion(InterfaceList[0]));
    memset(DMX_In, 0, sizeof(TDMXArray));
    memset(DMX_Out, 0, sizeof(TDMXArray));
    res = OpenLink(InterfaceList[0], &DMX_Out, &DMX_In);
    if(res != 1) {
        printf("Unable to open Interface, did you install the udev-rule?\n");
        exit(1);
    }
    printf("Connected\n");
    Sleep(1);
    SetInterfaceMode(InterfaceList[0], 2);
	return;
}

JNIEXPORT void JNICALL Java_jniGlue_Windowsclass_senddmx(JNIEnv *env,jobject obj,jint channel,jint value)
{
	int i;   
    for (int j = 0; j<2;j++) 
    {
		DMX_Out[channel] = value;
	}
	return;
}


JNIEXPORT void JNICALL Java_jniGlue_Windowsclass_closedmx(JNIEnv *env, jobject obj, jstring path)
{
	const char *nativeString = env->GetStringUTFChars(path, 0);
	HINSTANCE USBDMXDLL = LoadLibrary (nativeString) ;
	TCloseLink CloseLink;
	int i;
    CloseLink = (TCloseLink)GetProcAddress(USBDMXDLL, "CloseLink");
	printf("\nCLEANUP\n\n");

    for(i=0;i<=511;i++) 
    {
        DMX_Out[i] = 0;
    }
    Sleep(100);

    CloseLink(InterfaceList[0]);
	FreeLibrary (USBDMXDLL);
	return;
}

